package com.fyt.reachgo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fyt.reachgo.config.RabbitMQConfig;
import com.fyt.reachgo.domain.UserDisinterest;
import com.fyt.reachgo.domain.message.LikeMessage;
import com.fyt.reachgo.domain.Result;
import com.fyt.reachgo.domain.TravelGuide;
import com.fyt.reachgo.domain.UserLike;
import com.fyt.reachgo.mapper.TravelGuideMapper;
import com.fyt.reachgo.mapper.UserLikeMapper;
import com.fyt.reachgo.service.LikeService;
import com.fyt.reachgo.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class LikeServiceImpl implements LikeService{

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserLikeMapper userLikeMapper;

    @Autowired
    private TravelGuideMapper travelGuideMapper;

    /**
     * 切换点赞状态
     * @param userId 用户ID
     * @param guideId 路书ID
     * @return 操作结果和当前状态
     */
    public Result<Boolean> toggleLike(Long userId, Integer guideId) {
        // 参数校验
        if (userId == null || guideId == null) {
            return Result.error("参数不能为空");
        }

        String likeKey = "like:" + guideId + ":users";
        String countKey = "like:" + guideId + ":count";

        try {
            // 检查当前点赞状态
            Boolean isLiked = redisTemplate.opsForSet().isMember(likeKey, userId);
            boolean newStatus = !Boolean.TRUE.equals(isLiked);

            // Redis事务操作
            redisTemplate.execute(new SessionCallback<Object>() {
                @Override
                public Object execute(RedisOperations operations) throws DataAccessException {
                    operations.multi();

                    if (newStatus) {
                        operations.opsForSet().add(likeKey, userId);
                        operations.opsForValue().increment(countKey);
                    } else {
                        operations.opsForSet().remove(likeKey, userId);
                        operations.opsForValue().decrement(countKey);
                    }

                    return operations.exec();
                }
            });

            // 发送消息到RabbitMQ
            LikeMessage message = new LikeMessage(userId, guideId,
                    newStatus ? "like" : "unlike",
                    System.currentTimeMillis(),
                    newStatus);

            rabbitTemplate.convertAndSend(
                    RabbitMQConfig.LIKE_EXCHANGE,
                    RabbitMQConfig.LIKE_ROUTING_KEY,
                    message
            );

            log.info("用户{}切换路书{}点赞状态为{}", userId, guideId, newStatus ? "点赞" : "取消点赞");
            return Result.success(newStatus);
        } catch (Exception e) {
            log.error("用户{}切换路书{}点赞状态失败: {}", userId, guideId, e.getMessage());
            return Result.error("操作失败，请稍后重试");
        }
    }


}



